﻿namespace Hidistro.UI.SaleSystem.CodeBehind
{
    using Hidistro.Entities.Commodities;
    using Hidistro.Membership.Context;
    using Hidistro.SaleSystem.Catalog;
    using Hidistro.UI.Common.Controls;
    using System;
    using System.IO;
    using Hidistro.UI.SaleSystem.Tags;
    using Hidistro.Core;
    using System.Web.UI.WebControls;
    using System.Text;
    using System.Data;
    using Hidistro.ControlPanel.Commodities;
    using Hidistro.SqlDal.Commodities;
    using System.Web.UI.HtmlControls;
    using wnxd.javascript;
    using System.Text.RegularExpressions;
    using System.Collections.Generic;
    using System.Linq;
    using JSShop.Model;

    public class DetailPages_3q : HtmlTemplatedWebControl
    {
        Juse.Interface.ProductBrowser IProductBrowser = new Juse.Interface.ProductBrowser();
        private int productId;
        private wnxd_DetailPagesLocation DetailPagesLocation;
        private wnxd_ProductImages ProductImages;
        private Literal litProductName;
        private Literal litProductText;
        private Literal lblBuyPrice;
        private Literal lblMarkerPrice;
        private Literal lblProductCode;
        private Literal lblSaleCount;
        private Literal litBrosedNum;
        private Literal litSaleCounts;
        private HtmlGenericControl CountDown;
        private SKUSelector_3q SKUSelector_3q;
        private wnxd_SimilarProducts_3q wnxd_SimilarProducts_3q;
        private Literal litDescription;
        private Literal FavoriteNum;
        private DetailPages_ReviewList reviewList;
        private HtmlAnchor hpkProductConsultations;
        private DetailPages_ConsultationList consultationList;
        private wnxd_Shopping_LiList recommendProduct;
        private HtmlGenericControl cxxx;
        private Literal mjxx;
        private Literal hdyg;
        protected override void AttachChildControls()
        {
            this.DetailPagesLocation = (wnxd_DetailPagesLocation)this.FindControl("wnxd_DetailPagesLocation");
            this.ProductImages = (wnxd_ProductImages)this.FindControl("wnxd_ProductImages");
            this.litProductName = (Literal)this.FindControl("litProductName");
            this.litProductText = (Literal)this.FindControl("litProductText");
            this.lblBuyPrice = (Literal)this.FindControl("lblBuyPrice");
            this.lblMarkerPrice = (Literal)this.FindControl("lblMarkerPrice");
            this.lblProductCode = (Literal)this.FindControl("lblProductCode");
            this.lblSaleCount = (Literal)this.FindControl("lblSaleCount");
            this.litBrosedNum = (Literal)this.FindControl("litBrosedNum");
            this.litSaleCounts = (Literal)this.FindControl("litSaleCounts");
            this.CountDown = (HtmlGenericControl)this.FindControl("CountDown");
            this.SKUSelector_3q = (SKUSelector_3q)this.FindControl("SKUSelector_3q");
            this.wnxd_SimilarProducts_3q = (wnxd_SimilarProducts_3q)this.FindControl("wnxd_SimilarProducts_3q");
            this.litDescription = (Literal)this.FindControl("litDescription");
            this.FavoriteNum = (Literal)this.FindControl("FavoriteNum");
            this.reviewList = (DetailPages_ReviewList)this.FindControl("reviewList");
            this.hpkProductConsultations = (HtmlAnchor)this.FindControl("hpkProductConsultations");
            this.consultationList = (DetailPages_ConsultationList)this.FindControl("consultationList");
            this.recommendProduct = (wnxd_Shopping_LiList)this.FindControl("recommendProduct");
            this.cxxx = (HtmlGenericControl)this.FindControl("cxxx");
            this.mjxx = (Literal)this.FindControl("mjxx");
            this.hdyg = (Literal)this.FindControl("hdyg");
            if (this.Page.Request.HttpMethod == "GET")
            {
                vw_Hishop_BrowseProductList product = IProductBrowser.GetBrowseProductView(null, this.productId);
                if (product == null)
                {
                    this.Page.Response.Redirect(Globals.ApplicationPath + "/ResourceNotFound.aspx?errorMsg=" + Globals.UrlEncode("该件商品已经被管理员删除"));
                }
                else
                {
                    new Juse.Interface.DataModification().UpDateProductVistiCounts_Mem(this.productId);
                    if (product.SaleStatus == JSShop.Enum.ProductSaleStatus.UnSale)
                    {
                        this.Page.Response.Redirect(Globals.GetSiteUrls().UrlData.FormatUrl("unproductdetails", new object[] { this.productId }));
                    }
                    if (product.SaleStatus == JSShop.Enum.ProductSaleStatus.OnStock)
                    {
                        this.Page.Response.Redirect(Globals.ApplicationPath + "/ResourceNotFound.aspx?errorMsg=" + Globals.UrlEncode("该商品已入库"));
                    }
                    else
                    {
                        this.LoadPageSearch(product);
                        this.LoadControls(product);
                        this.SKUSelector_3q.ProductId = this.productId;
                        this.SKUSelector_3q.DataSource = IProductBrowser.GetSKUItemList(this.productId);
                        List<Hishop_ProductReviews> Reviews = IProductBrowser.GetProductReviews(this.productId);
                        this.hpkProductConsultations.HRef = "/ProductConsultationsAndReplay.aspx?productId=" + this.productId;
                        this.reviewList.DataSource = Reviews;
                        this.reviewList.DataBind();
                        List<Hishop_ProductConsultations> Consultations = IProductBrowser.GetProductConsultations(this.productId);
                        this.consultationList.DataSource = Consultations;
                        this.consultationList.DataBind();
                    }
                }
            }
        }

        private void LoadControls(vw_Hishop_BrowseProductList product)
        {
            this.DetailPagesLocation.CateGoryPath = product.MainCategoryPath.Remove(product.MainCategoryPath.Length - 1);
            this.ProductImages.ImageInfo = product;
            this.litProductName.Text = "<a href=\"" + Globals.GetSiteUrls().UrlData.FormatUrl("branddetails", product.BrandId) + "\">" + product.BrandName + "</a> " + product.ProductName;
            this.litProductText.Text = product.ProductText;
            this.lblSaleCount.Text = product.ReView.ToString();
            aspnet_Members member = null;
            Member m = HiContext.Current.User as Member;
            if (m != null) member = new json(m).TryConvert(typeof(aspnet_Members)) as aspnet_Members;
            List<Hishop_SKUs> skus = IProductBrowser.GetSkuList(member, product.ProductId);
            decimal MinSalePrice = this.GetMinSalePrice(skus);
            decimal MaxSalePrice = this.GetMaxSalePrice(skus);
            if (MinSalePrice == MaxSalePrice)
            {
                this.lblBuyPrice.Text = MinSalePrice.ToString("F0");
            }
            else
            {
                this.lblBuyPrice.Text = MinSalePrice.ToString("F0") + " - " + MaxSalePrice.ToString("F0");
            }
            this.lblMarkerPrice.Text = product.MarketPrice.Value.ToString("F0");
            this.lblProductCode.Text = product.ProductCode;
            //this.litBrosedNum.Text = product.VistiCounts.ToString();
            this.litSaleCounts.Text = product.ShowSaleCounts.ToString();
            this.litDescription.Text = Globals.ReplaceImgUrl(product.Description);
            //this.FavoriteNum.Text = (IProductBrowser.GetFavoriteCount(this.productId)).ToString();
            if (member != null)
            {
                List<int> list = IProductBrowser.GetFavoriteList(member, 0);
                this.recommendProduct.DataSource = IProductBrowser.GetCaiNiXiHuan(member, list, 3);
                this.recommendProduct.DataBind();
            }
            List<Hishop_Promotions> promotions = IProductBrowser.GetPromotions(product.ProductId);
            if (promotions != null && promotions.Count > 0)
            {
                this.cxxx.Visible = true;
                string str = null;
                foreach (Hishop_Promotions info in promotions)
                {
                    if (info != null)
                    {
                        if (str != null) str += "，";
                        str += info.Name;
                    }
                }
                this.mjxx.Text = "<em>促销</em> " + str + "<a href=\"\">详情 &gt;&gt;</a><br />";
            }
            Hishop_Promotions promotion = IProductBrowser.GetRecentPromotion(product.ProductId);
            if (promotion != null)
            {
                this.cxxx.Visible = true;
                this.hdyg.Text = "<em>活动预告</em> " + promotion.StartDate.ToString("MM月dd日 HH:mm") + " 该商品参加" + promotion.Name + "<a href=\"\">详情 &gt;&gt;</a><br>";
            }
        }

        private decimal GetMinSalePrice(ICollection<Hishop_SKUs> list)
        {
            if (list == null || list.Count == 0) return 0;
            decimal MinSalePrice = 79228162514264337593543950335M;
            foreach (Hishop_SKUs item in list)
            {
                if (item.SalePrice < MinSalePrice) MinSalePrice = item.SalePrice;
            }
            return MinSalePrice;
        }
        private decimal GetMaxSalePrice(ICollection<Hishop_SKUs> list)
        {
            if (list == null || list.Count == 0) return 0;
            decimal MaxSalePrice = 0;
            foreach (Hishop_SKUs item in list)
            {
                if (item.SalePrice > MaxSalePrice) MaxSalePrice = item.SalePrice;
            }
            return MaxSalePrice;
        }

        private void LoadPageSearch(vw_Hishop_BrowseProductList product)
        {
            if (!string.IsNullOrEmpty(product.Meta_KeyWords))
            {
                MetaTags.AddMetaKeywords(product.Meta_KeyWords, HiContext.Current.Context);
            }
            if (!string.IsNullOrEmpty(product.Meta_Description))
            {
                MetaTags.AddMetaDescription(product.Meta_Description, HiContext.Current.Context);
            }
            if (!string.IsNullOrEmpty(product.Title))
            {
                PageTitle.AddSiteNameTitle(product.Title);
            }
            else
            {
                PageTitle.AddSiteNameTitle(product.ProductName);
            }
        }
        protected override void OnInit(EventArgs e)
        {
            if (!int.TryParse(this.Page.Request.QueryString["productId"], out this.productId))
            {
                base.GotoResourceNotFound();
            }
            if (this.SkinName == null)
            {
                this.SkinName = "Skin-DetailPages_3q.html";
            }
            base.OnInit(e);
        }
        public string ReviewListPager()
        {
            this.AttachChildControls();
            List<Hishop_ProductReviews> Reviews = IProductBrowser.GetProductReviews(this.productId);
            this.reviewList.DataSource = Reviews;
            return this.reviewList.ReviewListPager();
        }
        public json ConsultationListPager()
        {
            this.AttachChildControls();
            List<Hishop_ProductConsultations> Consultations = IProductBrowser.GetProductConsultations(this.productId);
            this.consultationList.DataSource = Consultations;
            return this.consultationList.ConsultationListPager();
        }
        public json UserProductNotify()
        {
            json r = new json(new { error = true });
            if (HiContext.Current.User.IsAnonymous)
            {
                r["msg"] = "请登录后再订阅";
                return r;
            }
            decimal price;
            if (decimal.TryParse(this.Page.Request.Form["price"], out price) && price > 0)
            {
                string contact = this.Page.Request.Form["contact"];
                if (string.IsNullOrEmpty(contact))
                {
                    r["msg"] = "请输入联系方式";
                }
                else
                {
                    contact = contact.Trim();
                    Regex regex = new Regex(@"^1[3-8]\d{9}$");
                    Regex regex2 = new Regex(@"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?");
                    if (regex.IsMatch(contact))
                    {
                        this.AttachChildControls();
                        if (ProductBrowser.UserProductNotify(this.productId, HiContext.Current.User.UserId, price, contact, null))
                        {
                            r["error"] = false;
                        }
                        else
                        {
                            r["msg"] = "订阅失败";
                        }
                    }
                    else if (regex2.IsMatch(contact))
                    {
                        this.AttachChildControls();
                        if (ProductBrowser.UserProductNotify(this.productId, HiContext.Current.User.UserId, price, null, contact))
                        {
                            r["error"] = false;
                        }
                        else
                        {
                            r["msg"] = "订阅失败";
                        }
                    }
                    else
                    {
                        r["msg"] = "请输入正确的联系方式";
                    }
                }
            }
            else
            {
                r["msg"] = "请输入正确的价格";
            }
            return r;
        }
        public json AddFavorite()
        {
            json ret = new json(new { error = true });
            if (HiContext.Current.User.IsAnonymous)
            {
                ret["msg"] = "需要登录后才能关注";
            }
            else
            {
                Hishop_Favorite favorite = new Hishop_Favorite()
                {
                    ProductId = this.productId,
                    UserId = HiContext.Current.User.UserId,
                    Tags = "",
                    Remark = ""
                };
                IProductBrowser.SetFavorite(favorite);
                ret["error"] = false;
            }
            return ret;
        }
        public bool AddHistory()
        {
            BrowsedProductQueue.EnQueue(productId);
            return false;
        }
        public json Isvip()
        {
            json ret = new json(new { error = true });
            if (HiContext.Current.User.IsAnonymous)
            {
                ret["error"] = false;
            }
            return ret;
        }
    }
}
